import React, {useState,useEffect} from "react";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Button from "antd/lib/button";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import 'antd/dist/antd.less'
import Workflow from "@/services/workflow";
import { currentUser } from "@/services/auth";
import moment from "moment";
import DatePicker from "antd/lib/date-picker";
import 'braft-editor/dist/index.css'
import BraftEditor from 'braft-editor'

  const excludeControls = [ 'undo', 'redo', 'separator','line-height','letter-spacing','superscript', 'italic', 'subscript',
  'remove-styles','emoji','link','list-ul','list-ol','media','headings', 'blockquote', 'code',
   'hr', 'clear','font-size']
  const mwidth=document.querySelector('body').offsetWidth*0.4

function CreateCheckDialog({ bill_check, dialog }) {

  const [bill, setbill] = useState("");
  const [billtype, setbilltype] = useState(0);
  const [billid, setbillid] = useState(0);
  const [message, setMessage] = useState("");
  const [billdate, setbilldate] = useState(moment());
  const [status, setstatus] = useState(0);
  useEffect(() => {
    if (bill_check.billid === 0) return;
    let cancelLoading = false;
    if (!cancelLoading) {
      setbill(bill_check.bill);
      setbilltype(bill_check.billtype);
      setbillid(bill_check.billid);
      setMessage(BraftEditor.createEditorState(bill_check.message));
      setstatus(bill_check.status);
    }

    return () => {
      cancelLoading = true;
    };
  }, [bill_check]);
    function handleEditorChange(event) {
   // const value = trim(event.target.value);
    setMessage(event);
  }
    function handlebilldateChange(event) {
    const value = event;
    setbilldate(value);
  }
  function submitContent(){
    // 在编辑器获得焦点时按下ctrl+s会执行此方法
    // 编辑器内容提交到服务端之前，可直接调用contracteditor.toHTML()来获取HTML格式的内容
    //const htmlContent = message.toHTML()
    // this.setState({
    //   contracteditor: BraftEditor.createEditorState(htmlContent),
    //   templatecontent: htmlContent,
    // })
}
  function handleSubmit(event) {
    //  console.log(event);
    if(event>0) {
      if(event===1 && status===2){
        notification.error("单据已审核，不能重复审核！");
        return;
      }
      if(event===2 && status===0){
        notification.error("草稿状态，不能驳回！");
        return;
      }
      if(event===3 && status===0){
        notification.error("草稿状态，不能取消审核！");
        return;
      }
       if(billdate===null || billdate===undefined){
        notification.error("日期不能为空！");
        return;
      }
      const htmlContent = message.toHTML()
      let item = {
        bill: bill,
        billid: billid,
        next_type: event,
        billtype:billtype,
        message: message==="" ? "":htmlContent,
        userid: currentUser.id,
        billdate: billdate.format('YYYY-MM-DD'),
        orgunitid:bill_check.orgunitid,
      }
      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
            ///----------------------------------
              notification.success(data[0].message);
              dialog.close({success: true});
            } else {
              notification.error(data[0].message);
            }
          })
            .catch(error => {
              notification.error(error.message, error.detailedMessage);
            });
    }else{
      dialog.close({success: false});
    }
  }

  return (
  //  const formLayout = {labelCol: { span: 4 }, wrapperCol: { span: 14 },};
    
    <Modal
      {...dialog.props}
      footer={[<Button key='appove' onClick={() => handleSubmit(1)}>审核通过</Button>,
        <Button key='review' onClick={() =>handleSubmit(2)}>驳回</Button>,
        <Button key='appove' onClick={() => handleSubmit(3)}>取消审核</Button>,
        <Button key='back' onClick={() =>handleSubmit(0)}>取消</Button>,
      ]}
      title="单据审批"
      width={document.querySelector('body').offsetWidth*0.7}
      height={document.querySelector('body').offsetHeight*0.7}
      okText="同意"
      cancelText="取消"
      okButtonProps={{
        // disabled: !isValid || saveInProgress,
        // loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      // cancelButtonProps={{
      //   disabled: saveInProgress,
      // }}
      onOk={handleSubmit}
      // closable={!saveInProgress}
      // maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <DynamicComponent name="WorkflowDialogExtra" >
      <Form layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
        {/* <Row>
				  <Col > */}
            <Form.Item style={{ marginBottom: 5 }} label="审批建议">
            <BraftEditor
                    value={message}
                    excludeControls={excludeControls}
                    onChange={handleEditorChange}
                    onSave={submitContent}
                    contentStyle={{height: 250, minHeight: 200,width: mwidth, minWwidth: mwidth}}
                />
						</Form.Item>

            <Form.Item style={{ marginBottom: 5 }} label="审核日期">
            <DatePicker
              value={billdate}
               onChange={handlebilldateChange}
              placeholder="审核日期"
              autoFocus
            />
						</Form.Item>
      </Form>
      </DynamicComponent>
    </Modal>
  );
}

CreateCheckDialog.propTypes = {
  bill_check: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateCheckDialog);
